export default class {
    constructor(selector = document){
        this.selector = selector;
        this.update();
        this.lazy();
        var srollTarget = this.selector === document ? window : this.selector;
        srollTarget.addEventListener('scroll',()=>{
             //懒加载
             this.lazy();
        },false)
    }

    update(){
        this.list = this.selector.querySelectorAll('img[data-src]');
        this.lazy();
    }

    lazy(){
        let len = this.list.length;
        if(len ==0) return false;
        for(let i = 0;i<len;i++){
            let img = this.list[i];
            let attr = img.getAttribute('lazy');
            if(attr !== 'done' && attr !== 'loading'){
                //do login
                let rect = img.getBoundingClientRect();
                let winH = window.innerHeight;
                if(rect.top > -20 && rect.top < winH + 20){
                    this.load(img);
                }
            }
        }
    }

    load(img){
        let image = new Image;
        let src = img.getAttribute('data-src');
        img.setAttribute('lazy','loading');

        image.onload = function(){
            img.setAttribute('src',src);
            img.setAttribute('lazy','done');
        }

        image.onerror = function(e){
            img.setAttribute('lazy','error');
        }
        image.src = src;
    }
}